package com.keyinong.dingcan.pay;

import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import net.sourceforge.simcpux.Constants;
import net.sourceforge.simcpux.MD5;
import net.sourceforge.simcpux.Util;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.keyinong.dingcan.R;
import com.keyinong.dingcan.Tools.HttpTools;
import com.keyinong.dingcan.view.FanqiedingcanActivity;
import com.keyinong.dingcan.view.NewUsecouponsActivity;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**订单支付*/

public class PayActivity extends FragmentActivity {

	// 商户PID
	public static final String PARTNER = "2088021553844659";
	// 商户收款账号
	public static final String SELLER = "13567154389@163.com";
	// 商户私钥，pkcs8格式
	public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAM0/MR9V0JN2WxU+j8UzatC4A0WC2ZuGfKi5760T4wawOT5h4wgyaJyc8Zg23JtRZmbPD4Ez1nKYijBUD2rsg5TxvJQwiEn7F3Sdj2EoMXLXSmF3+dwFvss8bLrP/H1f1UF8D7w9Nc3brCQmTLsWRp5WhP83osN2LgZF0CabOz+JAgMBAAECgYAovb9xeeZSLy87U1TUjzVHww8bMDMj1RlPoMD7uTPacwaZ5HJdgSwU0m5+iX1W81yBUd7BBdoumyrrFvSMg/BGOB0g7HDb8krN6RIyfen4gSkdsamYv8knaPpR3AAzWUSyQ2qE/PIB2NkllaENJFv1snlhAJFFZL+HnpgwckSjhQJBAPxph3NKqRA7PMlBiJyVKB6Mp6uJl/VCWIQiVdLvsfmhUoas0IHqRwmlbY3/SdB1RJli40ZYpATs2FUMHDl1MnsCQQDQKgnk79nONoUC9crYx/1w3MMNSzPrnDSmlclnCcbdKN0RgvMkLricPpea/Gj/5byOfkZU27nmZ0AfA7NGayjLAkB97kSGz9QDZhqQqmJ3BK+sdi5dFdu7oGs7GUpKYA4iZksfJ+8rMfBZLrC27IwuNaORB1YuzaCfWG8iF1WpkQArAkB1CI2Thz4fcAuMRICNLLNS9us62CMSvjnjxqb7JUYHJWhU5hipKRNl1NMLsgmehZ1jR59nKjn0TeyBA2WRm8HNAkEAtRpz1YcxfXi5VqtE1uEpn0X64hxODuaCEs+s9xq1gLLNxVLZUYGXWNszEh/jABJg49VHla/G/A+jBK1hmUjgmA==";
	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";
	private static final int SDK_PAY_FLAG = 1;
	
	private static final String TAG = "MicroMsg.SDKSample.PayActivity";

	PayReq req;
	final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
//	TextView show;
	Map<String,String> resultunifiedorder;
	StringBuffer sb;
	
	/**余额支付*/
	private RelativeLayout rl_yue;
	private ImageView iv_yuechecked;
	private ImageView iv_yueunchecked;
	/**支付宝支付*/
	private RelativeLayout rl_zhifubao;
	private ImageView iv_zhifubaochecked;
	private ImageView iv_zhifubaounchecked;
	/**微信支付*/
	private RelativeLayout rl_weixin;
	private ImageView iv_weixinchecked;
	private ImageView iv_weixinunchecked;
	/**选择优惠券*/
	private RelativeLayout rl_youhuiquan;
	private TextView tv_shengyu;
	/**返回*/
	private ImageButton ib_back;
	/**确认支付*/
	private Button btn_pay;
	/**价格*/
	private TextView tv_price;
	private TextView tv_yueprice;
	private TextView tv_weixinprice;
	private TextView tv_balance;
	private String price;
	private int flag=1;
	private String orderid;
	private int length;
	private String off;
	private String couponid="0";
	private String token;
	private String weixinprice;
	/**网络请求*/
	HttpTools httpTools=null;
	private IWXAPI api;
	SharedPreferences spReg;
	Editor editor;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回�?要验证的信息

				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为�??9000”则代表支付成功，具体状态码代表含义可参考接口文�?
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(PayActivity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					//					SharedPreferences sp = getSharedPreferences("pay",
					//							Context.MODE_PRIVATE);
					//					String id = sp.getString("id", "");
					if (!couponid.equals("0")) {
						alipayuseconpons();
						Log.i("zq", "useconpons-------");
					}else {
						alipay();
						Log.i("zq", "alipay-------");
					}
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失�?
					// "8000"代表支付结果因为支付渠道原因或�?�系统原因还在等待支付结果确认，�?终交易是否成功以服务端异步�?�知为准（小概率状�?�）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(PayActivity.this, "支付结果确认�?",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(PayActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();
						btn_pay.setEnabled(true);
					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.newpay_external);
//		req = new PayReq();
//		sb=new StringBuffer();
//
//		msgApi.registerApp(Constants.APP_ID);
////		genPayReq();
//		GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
//		getPrepayId.execute();
//		
//		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		ib_back=(ImageButton)findViewById(R.id.ib_fanhui);
		ib_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		iv_yuechecked=(ImageView)findViewById(R.id.iv_yuechecked);
		iv_yueunchecked=(ImageView)findViewById(R.id.iv_yueunchecked);
		iv_zhifubaochecked=(ImageView)findViewById(R.id.iv_zhifubaochecked);
		iv_zhifubaounchecked=(ImageView)findViewById(R.id.iv_zhifubaounchecked);
		iv_weixinchecked=(ImageView)findViewById(R.id.iv_weixinchecked);
		iv_weixinunchecked=(ImageView)findViewById(R.id.iv_weixinunchecked);
		rl_yue=(RelativeLayout)findViewById(R.id.rl_yue);
		rl_zhifubao=(RelativeLayout)findViewById(R.id.rl_zhifubao);
		rl_weixin=(RelativeLayout)findViewById(R.id.rl_weixin);
		rl_youhuiquan=(RelativeLayout)findViewById(R.id.rl_youhuiquan);
		tv_shengyu=(TextView)findViewById(R.id.tv_shengyu);
		tv_balance=(TextView)findViewById(R.id.tv_balance);
		tv_price=(TextView)findViewById(R.id.tv_price);
		tv_yueprice=(TextView)findViewById(R.id.tv_yueprice);
		tv_weixinprice=(TextView)findViewById(R.id.tv_weixinprice);
		btn_pay=(Button)findViewById(R.id.pay);
		price = getIntent().getStringExtra("price");		
		orderid=getIntent().getStringExtra("orderid");
		weixinprice = ""+(int)(Double.parseDouble(price)*100);
		Log.i("zq", "weixinprice--------------"+weixinprice);
		Log.i("info", "payorderid--------------"+orderid);
		spReg = getSharedPreferences("weixinpay",
				Context.MODE_PRIVATE);
		editor = spReg.edit();
		editor.putString("orderid", orderid);
		editor.putString("coupons", "0");
		editor.commit();
		rl_yue.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				flag=3;
				iv_yuechecked.setVisibility(View.VISIBLE);
				iv_yueunchecked.setVisibility(View.GONE);
				iv_zhifubaochecked.setVisibility(View.GONE);
				iv_zhifubaounchecked.setVisibility(View.VISIBLE);
				iv_weixinchecked.setVisibility(View.GONE);
				iv_weixinunchecked.setVisibility(View.VISIBLE);
			}
		});
		rl_zhifubao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				flag=1;
				iv_yuechecked.setVisibility(View.GONE);
				iv_yueunchecked.setVisibility(View.VISIBLE);
				iv_zhifubaochecked.setVisibility(View.VISIBLE);
				iv_zhifubaounchecked.setVisibility(View.GONE);
				iv_weixinchecked.setVisibility(View.GONE);
				iv_weixinunchecked.setVisibility(View.VISIBLE);
			}
		});
		rl_weixin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				flag=2;
				iv_yuechecked.setVisibility(View.GONE);
				iv_yueunchecked.setVisibility(View.VISIBLE);
				iv_zhifubaochecked.setVisibility(View.GONE);
				iv_zhifubaounchecked.setVisibility(View.VISIBLE);
				iv_weixinchecked.setVisibility(View.VISIBLE);
				iv_weixinunchecked.setVisibility(View.GONE);
			}
		});
		btn_pay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (flag==3) {
					if (!couponid.equals("0")) {
					useconpons();
					btn_pay.setEnabled(false);
					Log.i("zq", "useconpons-------");
				}else {
					Balancepay();
					btn_pay.setEnabled(false);
					Log.i("zq", "Balancepay-------");
				}
					Log.i("zq", "余额支付");
				}else if(flag==1){
					Log.i("zq", "支付宝支付");
					pay(v);
					btn_pay.setEnabled(false);
				}else if(flag==2){
					sendPayReq();
				}
				
			}
		});
		//		SharedPreferences sp = getSharedPreferences("pay",
		//				Context.MODE_PRIVATE);
		//		String id = sp.getString("id", "");
//		String id = getIntent().getStringExtra("orderid2");
//		Log.i("shi", "id---"+id);
		
		//		price = sp.getString("price", "");
//		price=getIntent().getStringExtra("total");
		tv_price.setText("￥"+price);
		tv_yueprice.setText("￥"+price);
		tv_weixinprice.setText("￥"+price);
		Balance();
		Coupons();
		tv_shengyu.setText("无可用优惠券");
		rl_youhuiquan.setEnabled(false);
		rl_youhuiquan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(PayActivity.this, NewUsecouponsActivity.class);
				intent.putExtra("orderid", orderid);
				intent.putExtra("price", price);
				startActivityForResult(intent, 2);
				//	finish();
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("zq", "requestCode---------"+requestCode);
		Log.i("zq", "resultCode---------"+resultCode);
		//		Log.i("zq", "data---------"+data.getStringExtra("orderid"));
		switch(resultCode){  
		case 1:  
//			couponid
			tv_shengyu.setText("可用"+length+"张");
			price = getIntent().getStringExtra("price");
			weixinprice = ""+(int)(Double.parseDouble(price)*100);
			tv_price.setText("￥"+price);
			tv_yueprice.setText("￥"+price);
			tv_weixinprice.setText("￥"+price);
			spReg = getSharedPreferences("weixinpay",
					Context.MODE_PRIVATE);
			editor = spReg.edit();
			editor.putString("coupons", "0");
			editor.commit();
		case 2:  
			Bundle bundle = data.getExtras();  
			off = bundle.getString("off");
			couponid = bundle.getString("couponid");
			price = getIntent().getStringExtra("price");
			weixinprice = ""+(int)(Double.parseDouble(price)*100);
			if (!off.equals("0")) {
				rl_youhuiquan.setVisibility(View.VISIBLE);
				//off = getIntent().getStringExtra("off");
				Log.i("zq", "off-----"+off);
				Log.i("zq", "couponid-----"+couponid);
				Log.i("zq", "price-----"+price);
				spReg = getSharedPreferences("weixinpay",
						Context.MODE_PRIVATE);
				editor = spReg.edit();
				editor.putString("coupons", couponid);
				editor.commit();
				double youhui = Double.parseDouble(price)-Integer.parseInt(off);
				if (youhui<=0) {
					tv_price.setText("￥"+"0");
					tv_yueprice.setText("￥"+"0");
					tv_weixinprice.setText("￥"+"0");
				}else {
					tv_price.setText("￥"+youhui);
					price=""+youhui;
					weixinprice = ""+(int)(Double.parseDouble(price)*100);
					tv_yueprice.setText("￥"+youhui);
					tv_weixinprice.setText("￥"+youhui);
				}
				
				tv_shengyu.setText("减"+off+"元");
			}

		}  
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		req = new PayReq();
		sb=new StringBuffer();

		msgApi.registerApp(Constants.APP_ID);
//		genPayReq();
		GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
		getPrepayId.execute();
		
		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
	}
	/**查询余额*/
	private void Balance() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");
		if (httpTools == null) {
			httpTools = new HttpTools(PayActivity.this);
		}
		httpTools.getBalance(token,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
					Log.i("zq", "balance---"+response.toString());
					if (code == true) {
						String data=response.getString("data");
						//						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
						//										view.setBackgroundResource(R.drawable.shouchang1);
						tv_balance.setText("￥"+data);
					} else {
						Toast.makeText(PayActivity.this, msg, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	/**获取优惠券*/
	private void Coupons() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");
		String orderid=getIntent().getStringExtra("orderid");
				Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(PayActivity.this);
		}
		httpTools.getCoupons(token,orderid, new JsonCoupons());
	}
	public class JsonCoupons extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONArray response) {
			// TODO Auto-generated method stub
			super.onSuccess(statusCode, headers, response);
			try {
				
				Log.i("info",response.toString());
				for (int i = 0; i < response.length(); i++) {
					JSONObject data = response.getJSONObject(i);
					String id=data.getString("id");
					String couponno=data.getString("couponno");
					String more=data.getString("more");
					String off=data.getString("off");
					//					typelist.add(new AddressEntity(id, name, lot, lat));
				}
				length=response.length();
				Log.i("zq", "length-----------------"+length);
				if (response.length()==0) {
					tv_shengyu.setText("无可用优惠券");
					rl_youhuiquan.setEnabled(false);
				}else {
					
					//					if (off.equals("null")) {
					//						tv_shengyu.setText("�?"+off);
					//					}else {
					rl_youhuiquan.setEnabled(true);
					tv_shengyu.setText("可用"+response.length()+"张");
					//					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/**使用优惠券*/
	private void useconpons() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");

		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(PayActivity.this);
		}
		httpTools.updateCoupon(token,couponid,orderid,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
//					Log.i("zq", "balancepay---"+response.toString());
					if (code == true) {
						//						String data=response.getString("data");
//						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
//						Intent intent = new Intent();
//						intent.setClass(BalancepayActivity.this, FanqiedingcanActivity.class);
//						startActivity(intent);
						//										view.setBackgroundResource(R.drawable.shouchang1);
						//						tv_balance.setText("�?"+data+"�?");
						Log.i("zq", "useconpons----成功");
						resetbalancepay();
					} else {
						Toast.makeText(PayActivity.this, msg, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	/**余额支付*/
	private void Balancepay() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");

		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(PayActivity.this);
		}
		httpTools.submitpay(token,orderid,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
					Log.i("zq", "balancepay---"+response.toString());
					if (code == true) {
						//						String data=response.getString("data");
						Toast.makeText(PayActivity.this, msg, Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.setClass(PayActivity.this, FanqiedingcanActivity.class);
						startActivity(intent);
						finish();
						//										view.setBackgroundResource(R.drawable.shouchang1);
						//						tv_balance.setText("�?"+data+"�?");
					} else {
						Toast.makeText(PayActivity.this, msg, Toast.LENGTH_SHORT).show();
						btn_pay.setEnabled(true);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	
	/**余额支付失败*/
	private void resetbalancepay() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");

		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(PayActivity.this);
		}
		httpTools.submitpay(token,orderid,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
					Log.i("zq", "balancepay---"+response.toString());
					if (code == true) {
						//						String data=response.getString("data");
						Toast.makeText(PayActivity.this, msg, Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.setClass(PayActivity.this, FanqiedingcanActivity.class);
						startActivity(intent);
						finish();
						//										view.setBackgroundResource(R.drawable.shouchang1);
						//						tv_balance.setText("�?"+data+"�?");
					} else {
						Toast.makeText(PayActivity.this, msg, Toast.LENGTH_SHORT).show();
						btn_pay.setEnabled(true);
						resetconpons();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	/**支付宝支付(使用优惠券)*/
	private void alipayuseconpons() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");

		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(PayActivity.this);
		}
		httpTools.updateCoupon(token,couponid,orderid,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
//					Log.i("zq", "balancepay---"+response.toString());
					if (code == true) {
						//						String data=response.getString("data");
//						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
//						Intent intent = new Intent();
//						intent.setClass(BalancepayActivity.this, FanqiedingcanActivity.class);
//						startActivity(intent);
						//										view.setBackgroundResource(R.drawable.shouchang1);
						//						tv_balance.setText("�?"+data+"�?");
						Log.i("zq", "useconpons----成功");
						alipay();
					} else {
						Toast.makeText(PayActivity.this, msg, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	/**支付宝支付*/
	private void alipay(){
		orderid = getIntent().getStringExtra("orderid");
		Log.i("shi", "id---"+orderid);
		if(httpTools==null){
			httpTools = new HttpTools(getApplicationContext());
		}
		httpTools.aliPay(token,orderid,"1", new JsonHttpResponseHandler(){
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
//					Log.i("zq", "balance---"+response.toString());
					if (code == true) {
//						String data=response.getString("data");
//						Toast.makeText(PayDemoActivity.this, msg, Toast.LENGTH_SHORT).show();
						//										view.setBackgroundResource(R.drawable.shouchang1);
//						tv_balance.setText("�?"+data);
						Intent intent = new Intent();
						intent.setClass(getApplicationContext(), FanqiedingcanActivity.class);
						startActivity(intent);
						finish();
					} else {
						Toast.makeText(PayActivity.this, msg, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
	}
	/**支付失败返回优惠券*/
	private void resetconpons() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");

		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(PayActivity.this);
		}
		httpTools.resetCoupon(token,couponid,orderid,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
					Log.i("zq", "resetconpons---"+response.toString());
					if (code == true) {
						
					} else {
						Toast.makeText(PayActivity.this, msg, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(View v) {
		if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE)
				|| TextUtils.isEmpty(SELLER)) {
			new AlertDialog.Builder(this)
			.setTitle("警告")
			.setMessage("�?要配置PARTNER | RSA_PRIVATE| SELLER")
			.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
				public void onClick(
						DialogInterface dialoginterface, int i) {
					//
					finish();
				}
			}).show();
			return;
		}

		String orderInfo = getOrderInfo("番茄订餐", "企业订餐",price );

		/**
		 * 特别注意，这里的签名逻辑�?要放在服务端，切勿将私钥泄露在代码中�?
		 */
		String sign = sign(orderInfo);
		try {
			/**
			 * 仅需对sign 做URL编码
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		/**
		 * 完整的符合支付宝参数规范的订单信�?
		 */
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构�?�PayTask 对象
				PayTask alipay = new PayTask(PayActivity.this);
				// 调用支付接口，获取支付结�?
				String result = alipay.pay(payInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本�?
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	private String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账�?
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单�?
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步�?�知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm"
				+ "\"";

		// 服务接口名称�? 固定�?
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型�? 固定�?
		orderInfo += "&payment_type=\"1\"";

		// 参数编码�? 固定�?
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭�??
		// 取�?�范围：1m�?15d�?
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）�?
		// 该参数数值不接受小数点，�?1.5h，可转换�?90m�?
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支�?
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可�?
		orderInfo += "&return_url=\"m.alipay.com\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该�?�在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签�?
	 * 
	 * @param content
	 *            待签名订单信�?
	 */
	private String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}
	
	
	/**以下是微信支付*/
	
	/**
	 生成签名
	 */

	private String genPackageSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);
		

		String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",packageSign);
		return packageSign;
	}
	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

       this.sb.append("sign str\n"+sb.toString()+"\n\n");
		String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",appSign);
		return appSign;
	}
	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<"+params.get(i).getName()+">");


			sb.append(params.get(i).getValue());
			sb.append("</"+params.get(i).getName()+">");
		}
		sb.append("</xml>");

		Log.e("orion",sb.toString());
		return sb.toString();
	}

	private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String,String>> {

//		private ProgressDialog dialog;


		@Override
		protected void onPreExecute() {
//			dialog = ProgressDialog.show(PayActivity.this, getString(R.string.app_tip), getString(R.string.getting_prepayid));
		}

		@Override
		protected void onPostExecute(Map<String,String> result) {
//			if (dialog != null) {
//				dialog.dismiss();
//			}
			sb.append("prepay_id\n"+result.get("prepay_id")+"\n\n");
//			show.setText(sb.toString());

			resultunifiedorder=result;
			genPayReq();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected Map<String,String>  doInBackground(Void... params) {

			String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
			String entity = genProductArgs();

			Log.e("orion",entity);

			byte[] buf = Util.httpPost(url, entity);

			String content = new String(buf);
			Log.e("orion", content);
			Map<String,String> xml=decodeXml(content);

			return xml;
		}
	}



	public Map<String,String> decodeXml(String content) {

		try {
			Map<String, String> xml = new HashMap<String, String>();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(new StringReader(content));
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {

				String nodeName=parser.getName();
				switch (event) {
					case XmlPullParser.START_DOCUMENT:

						break;
					case XmlPullParser.START_TAG:

						if("xml".equals(nodeName)==false){
							//实例化student对象
							xml.put(nodeName,parser.nextText());
						}
						break;
					case XmlPullParser.END_TAG:
						break;
				}
				event = parser.next();
			}

			return xml;
		} catch (Exception e) {
			Log.e("orion",e.toString());
		}
		return null;

	}


	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	
	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}
	


	private String genOutTradNo() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	

  //
	private String genProductArgs() {
		StringBuffer xml = new StringBuffer();

		try {
			String	nonceStr = genNonceStr();
			xml.append("</xml>");
           List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
			packageParams.add(new BasicNameValuePair("body", "久瑞餐饮"));
			packageParams.add(new BasicNameValuePair("input_charset", "UTF-8"));
			packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID));
			packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			packageParams.add(new BasicNameValuePair("notify_url", "http://121.40.35.3/test"));
			packageParams.add(new BasicNameValuePair("out_trade_no",genOutTradNo()));
			packageParams.add(new BasicNameValuePair("spbill_create_ip","127.0.0.1"));
			packageParams.add(new BasicNameValuePair("total_fee", weixinprice));
			packageParams.add(new BasicNameValuePair("trade_type", "APP"));


			String sign = genPackageSign(packageParams);
			packageParams.add(new BasicNameValuePair("sign", sign));


			String xmlstring = toXml(packageParams);
           //改变拼接之后xml字符串格式
           return new String(xmlstring.toString().getBytes(), "ISO8859-1");
//			return xmlstring;

		} catch (Exception e) {
			Log.e(TAG, "genProductArgs fail, ex = " + e.getMessage());
			return null;
		}
		

	}
	private void genPayReq() {

		req.appId = Constants.APP_ID;
		req.partnerId = Constants.MCH_ID;
		req.prepayId = resultunifiedorder.get("prepay_id");
		req.packageValue = "Sign=WXPay";
		req.nonceStr = genNonceStr();
		req.timeStamp = String.valueOf(genTimeStamp());


		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

		req.sign = genAppSign(signParams);

		sb.append("sign\n"+req.sign+"\n\n");

//		show.setText(sb.toString());
		Log.e("orion", signParams.toString());

	}
	private void sendPayReq() {
		if (msgApi.isWXAppInstalled()==false) {
			Toast.makeText(PayActivity.this, "您没有安装微信，无法完成支付",Toast.LENGTH_SHORT).show();		
			btn_pay.setEnabled(true);
		}else {
			msgApi.registerApp(Constants.APP_ID);
		    msgApi.sendReq(req);
		    btn_pay.setEnabled(false);
		    finish();
		}
		
	}

}
